<template>
  <div class="agentList divBox">
    <el-card class="box-card" shadow="hover">
      <template class="clearfix" v-slot:header>
        <div class="container">
          <el-form :model="disForm" label-width="72px" ref="spreadRefs" class="spreadCls">
            <el-row :gutter="20">
              <el-col v-bind="grid">
                <el-form-item label="代理角色：" class="selectFormWidth100">
                  <el-select v-model="disForm.roleId" placeholder="请选择代理角色" size="small" clearable @change="getList('1')">
                    <el-option label="全部" :value="-1"></el-option>
                    <el-option :label="item.name" :value="item.id" v-for="item in tableAgentRolesList" :key="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col v-bind="grid">
                <el-form-item label="搜索：" class="search-select">
                  <el-input v-model="disForm.keyword" placeholder="请输入用户名或手机号" size="small" clearable>
                    <el-button slot="append" icon="el-icon-search" size="small" @click="getList('1')"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addAgent">添加代理</el-button>
        <el-tooltip :disabled="!disabled" class="ml10" effect="dark" content="本页至少选择一项" placement="bottom">
          <div style="display: inline-block;">
            <el-button :disabled="disabled" size="small" icon="el-icon-close" type="primary" @click="delAgent(null)">批量删除代理</el-button>
          </div>
        </el-tooltip>
      </template>
      <el-table
        v-loading="disLoading"
        :data="disList"
        style="width: 100%;"
        size="mini"
        class="table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" min-width="55"></el-table-column>
        <el-table-column prop="id" label="ID" align="center" min-width="50"></el-table-column>
        <el-table-column label="头像" min-width="60">
          <template slot-scope="{ row }">
            <div class="taoBox_img" v-viewer>
              <img v-lazy="$uploadURL(row.user.headImage)" :alt="$uploadURL(row.user.headImage)">
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" min-width="130">
          <template slot-scope="{ row }">
            <div v-if="row.user" class="userInfo">
              <div v-if="row.user.nickName">昵称：{{ row.user.nickName }}</div>
              <div v-if="row.user.realName">姓名：{{ row.user.realName }}</div>
              <div v-if="row.user.mobile">电话：{{ row.user.mobile }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户类型" align="center" min-width="100">
          <template slot-scope="{ row }">
            <span v-if="row.user">{{ row.user.registerFrom }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" min-width="60">
        <template slot-scope="{ row }">
          <span v-if="row.user">{{ row.user.gender | genderFilter }}</span>
        </template>
      </el-table-column>
        <el-table-column label="地区" align="center" min-width="250">
          <template slot-scope="{ row }">
            <span v-if="row.user">{{ row.user.address }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="代理名称" align="center" min-width="120"></el-table-column>
        <el-table-column label="代理商" align="center" min-width="150">
          <template slot-scope="{ row }">
            <span>{{ row.agentRoleId | agentRoleFilter }}({{ row.agentRole.agentLevelId | agentLevelFilter }})</span>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="代理电话" align="center" min-width="120"></el-table-column>
        <el-table-column label="提成" align="center" min-width="120">
          <template slot-scope="{ row }">
            <span>{{ row.commission }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="上级代理信息" min-width="140">
          <template slot-scope="{ row }">
            <div v-if="row.refAgent">
              <span v-if="row.refAgent.name">姓名：{{ row.refAgent.name }}</span><br/>
              <span v-if="row.refAgent.mobile">电话：{{ row.refAgent.mobile }}</span><br/>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230" fixed="right" align="center">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="cus(row.id)">客户列表</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" size="small" @click="edit(row.id)">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" size="small" @click="delAgent(row.id)">删除</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-dropdown class="ml10" placement="bottom">
              <span class="el-dropdown-link">
                更多<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="dropOrder(row.id)">推广订单</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="spreadBox">
        <pagination
          v-show="pagination.total > 0"
          :total="pagination.total"
          :page.sync="pagination.page"
          :limit.sync="pagination.limit"
          :page-sizes="[10, 20, 30, 50]"
          @pagination="replyChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
  import {
    getAgentListApi,
    getRolesListApi,
    DELETBatchAgentApi as delBatchAgentApi
  } from '@/api/agent';

  let _this;

  export default {
    name: 'Index',
    data() {
      return {
        grid: {
          xl: 5,
          lg: 7,
          md: 12,
          sm: 12,
          xs: 24
        },
        disForm: {
          keyword: '',
          roleId: ''
        },
        pagination: {
          page: 1,
          limit: 10,
          total: 0
        },
        tableAgentRolesList: [],
        disList: [],
        refAgentList: [],
        del: [],
        disLoading: false,
        tableLoading: false,
        disabled: true
      };
    },
    beforeCreate() {
      _this = this;
    },
    filters: {
      agentLevelFilter(val) {
        for (let i = 0; i < _this.tableAgentRolesList.length; i++) {
          if (val == _this.tableAgentRolesList[i].level) return _this.tableAgentRolesList[i].levelName;
        };
      },
      agentRoleFilter(val) {
        for (let i = 0; i < _this.tableAgentRolesList.length; i++) {
          if (val == _this.tableAgentRolesList[i].id) return _this.tableAgentRolesList[i].name;
        };
      }
    },
    mounted() {
      this.getList();
      this.getAgentRoles();
    },
    methods: {
      /**
       * 行选中时
       */
      handleSelectionChange(val) {
        this.$set(this, 'del', val.map((item) => item.id));
        console.log(this.del);
        if (val.length > 0)
          this.$set(this, 'disabled', false);
        else
          this.$set(this, 'disabled', true);
      },
      /**
       * 添加代理
       */
      addAgent() {
        const _this = this;
        _this.$modal({
          componentProps: {
            isEdit: 0
          },
          component: (resolve) => require(['./components/editAgent'], resolve),
          props: {
            title: '添加',
            customClass: 'zdyDialogCls editAgentDialogCls',
            width: '100%',
            closeOnClickModal: false
          },
          methods: {
            getAgentList() {
              _this.getList('1');
            }
          }
        });
      },
      /**
       * 客户列表
       */
      cus(id) {
        const _this = this;
        _this.$modal({
          componentProps: {
            id: id
          },
          component: (resolve) => require(['./components/cusList'], resolve),
          props: {
            title: '客户列表',
            customClass: 'zdyDialogCls cusDialogCls',
            width: '100%',
            closeOnClickModal: false
          },
          methods: {}
        });
      },
      /**
       * 推广订单
       */
      dropOrder(id) {
        const _this = this;
        _this.$modal({
          componentProps: {
            id: id
          },
          component: (resolve) => require(['./components/promotionOrder'], resolve),
          props: {
            title: '推广订单',
            customClass: 'zdyDialogCls promotionOrderDialogCls',
            width: '100%',
            closeOnClickModal: false
          },
          methods: {}
        });
      },
      /**
       * 删除
       */
      delAgent(id) {
        id || (this.del.length !== 0 && !this.disabled) ? this.$confirm(`删除代理商`, {
          title: `删除代理商`,
          message: this.$createElement('div', null, ['确定要删除代理商吗？', '删除代理商后将无法恢复，请谨慎操作！'].map((item) => this.$createElement('p', null, item))),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delBatchAgentApi(!id ? `(${this.del.join()})` : id).then((res) => {
            if (!id && res) return this.$message.warning(res);
            this.$message.success('删除代理商成功！');
            this.getList('1');
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: `已取消删除代理商`
          });
        }) : this.$message.warning('请至少选择一条数据');
      },
      /**
       * 编辑
       */
      edit(id) {
        const _this = this;
        _this.$modal({
          componentProps: {
            editId: id,
            isEdit: 1
          },
          component: (resolve) => require(['./components/editAgent'], resolve),
          props: {
            title: '编辑',
            customClass: 'zdyDialogCls editAgentDialogCls',
            width: '100%',
            closeOnClickModal: false
          },
          methods: {
            getAgentList() {
              _this.getList('1');
            }
          }
        });
      },
      /**
       * 获取代理商角色信息
       */
      getAgentRoles() {
        getRolesListApi({
          pageNumber: 1,
          pageSize: 30
        }).then(res => {
          this.$set(this, 'tableAgentRolesList', res.data);
        });
      },
      /**
       * 获取代理商列表
       */
      getList(num) {
        this.$set(this, 'tableLoading', true);
        getAgentListApi({
          pageNumber: num ? num : this.pagination.page,
          pageSize: this.pagination.limit,
          orderBy: 'Id desc',
          keyword: this.disForm.keyword,
          agentRoleId: this.disForm.roleId ? this.disForm.roleId : -1
        }).then(res => {
          this.$set(this, 'disList', res.data);
          this.$set(this.pagination, 'total', res.head.totalCount);
          this.$set(this, 'tableLoading', false);
        }).catch(() => {
          this.$set(this.pagination, 'total', 0);
          this.$set(this, 'disList', []);
          this.$set(this, 'tableLoading', false);
        });
      },
      replyChange(reply) {
        this.$set(this.pagination, 'page', reply.page);
        this.$set(this.pagination, 'limit', reply.limit);
        this.getList();
      }
    }
  }
</script>

<style lang="scss" scoped>
  .agentList {
    .taoBox_img {
      width: 36px;
      height: 36px;
      border-radius: 4px;
      overflow: hidden;
      cursor: pointer;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .el-dropdown-link {
      cursor: pointer;
      color: #409EFF;
      font-size: 12px;
    }
    .el-icon-arrow-down {
      font-size: 12px;
    }
  }
</style>

<style lang="scss">
  .el-dialog.cusDialogCls,
  .el-dialog.editAgentDialogCls {
    max-width: 960px;
  }
  .el-dialog.promotionOrderDialogCls {
    max-width: 900px;
  }
</style>
